package com.cs543.j.client.ui;

import java.util.Date;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.cs543.j.client.MobileCloudClient;
import com.cs543.j.client.R;
import com.cs543.j.client.cloudService.Client;
import com.cs543.j.client.cloudService.LocalClient;
import com.cs543.j.client.cloudService.RemoteClient;

public class ClientListViewer extends Activity {

	
	Map<String, String> m_clientMap;
	ListView clientListView;
	ClientListAdapter listViewAdapter;
	Vector<RemoteClient> remoteClientList;
	Handler uiHandler;

	public static final String INTENT_KEY_CLOUD_STORAGE_SELECTION = "selelction";
	public static final String INTENT_KEY_CLOUD_URL = "url";
			
	boolean isSelection;
	
	RemoteClient selection;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.client_list_viewer);

		

		Intent intent = this.getIntent();
		isSelection = intent.getBooleanExtra(INTENT_KEY_CLOUD_STORAGE_SELECTION, false);

		clientListView = (ListView) this.findViewById(R.id.client_list_viewer_list);
		

		clientListView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				selection = (RemoteClient) listViewAdapter.getItem(arg2);
				Intent explorer = new Intent(ClientListViewer.this, StorageExplorer.class);
				if (isSelection) {
					explorer.putExtra(StorageExplorer.INTENT_KEY_IS_LOCAL_SD_STORAGE, getIntent().getBooleanExtra(StorageExplorer.INTENT_KEY_IS_LOCAL_SD_STORAGE, false));
					explorer.putExtra(StorageExplorer.INTENT_KEY_DIRECTORY_SELECTION, getIntent().getBooleanExtra(StorageExplorer.INTENT_KEY_DIRECTORY_SELECTION, false));
					explorer.putExtra(StorageExplorer.INTENT_KEY_FILE_SELECTION, getIntent().getBooleanExtra(StorageExplorer.INTENT_KEY_FILE_SELECTION, false));
					explorer.putExtra(StorageExplorer.INTENT_KEY_REMOTE_NAME, selection.getName());
					explorer.putExtra(StorageExplorer.INTENT_KEY_REMOTE_URL, selection.getUrl());
					ClientListViewer.this.startActivityForResult(explorer, StorageExplorer.REQUEST_SELECTION);
				} else {
					explorer.putExtra(StorageExplorer.INTENT_KEY_IS_LOCAL_SD_STORAGE, false);
					explorer.putExtra(StorageExplorer.INTENT_KEY_DIRECTORY_SELECTION, false);
					explorer.putExtra(StorageExplorer.INTENT_KEY_FILE_SELECTION, false);
					explorer.putExtra(StorageExplorer.INTENT_KEY_REMOTE_NAME, selection.getName());
					explorer.putExtra(StorageExplorer.INTENT_KEY_REMOTE_URL, selection.getUrl());
					ClientListViewer.this.startActivity(explorer);
				}
				
			}
		});

		uiHandler = new Handler();
		
		this.refreshClientList();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.client_list_viewer_menu, menu);
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		if(item.getItemId() == R.id.client_list_view_refresh)
		{
			this.refreshClientList();
			return true;
		}
		else
			return super.onMenuItemSelected(featureId, item);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(resultCode == Activity.RESULT_OK )
		{
			Intent intent = new Intent();
			intent.putExtra(StorageExplorer.INTENT_KEY_RESULT_PATH, data.getStringExtra(StorageExplorer.INTENT_KEY_RESULT_PATH));
			intent.putExtra(INTENT_KEY_CLOUD_URL, selection.getUrl());
			setResult(Activity.RESULT_OK, intent);
			Log.d("ClientListViewer" , "Local File Selection : " + data.getStringExtra(StorageExplorer.INTENT_KEY_RESULT_PATH) );
			finish();
		}
		else
			super.onActivityResult(requestCode, resultCode, data);
	}
	
	public void refreshClientList()
	{
		Thread t = new Thread(new Runnable() {
			
			public void run() {
				Map<String, String> clientList = MobileCloudClient.m_udpClient.get();
				Set<String> keySet = clientList.keySet();
				remoteClientList = new Vector<RemoteClient>();
				remoteClientList.add(RemoteClient.getLocalCloudClient());
				
				for(String name : keySet)
				{
					if(!name.equals(MobileCloudClient.clientName))
						remoteClientList.add(new RemoteClient(name, clientList.get(name) ));
				}
				
				uiHandler.post(new Runnable() {
					
					public void run() {
						listViewAdapter = new ClientListAdapter(remoteClientList);
						clientListView.setAdapter(listViewAdapter);						
					}
				});
			}
		});
		
		t.start();
	}


	private class ClientListAdapter implements ListAdapter {
		private Vector<RemoteClient> clientList;

		public ClientListAdapter(Vector<RemoteClient> clientList) {
			super();

			this.clientList = clientList;
			
			//clientList.add(new RemoteClient("Test Cloud Storage", "http://localhost:8080/"));
		}

		public int getCount() {
			return this.clientList.size();
		}

		public Object getItem(int position) {
			return this.clientList.get(position);
		}

		public long getItemId(int position) {
			return 1;
		}

		public int getItemViewType(int position) {
			return 1;
		}

		public View getView(int position, View convertView, ViewGroup parent) {

			LayoutInflater layoutInflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View view = layoutInflater.inflate(R.layout.client_list_viewer_element, null);

			ImageView icon = (ImageView) view.findViewById(R.id.client_list_viewer_element_icon);
			TextView text = (TextView) view.findViewById(R.id.client_list_viewer_element_text);

			if (clientList.get(position).isLocalClient() && clientList.get(position).getName().equals(RemoteClient.LOCAL_CLOUD_NAME)) {
				icon.setImageResource(R.drawable.local_cloud_storage);
			} else if (clientList.get(position).isLocalClient() && clientList.get(position).getName().equals(LocalClient.LOCAL_SDCARD_NAME)) {
				icon.setImageResource(R.drawable.local_sd_storage);
			} else {
				icon.setImageResource(R.drawable.remote_storage);
			}
			text.setText(clientList.get(position).getName());

			return view;
		}

		public int getViewTypeCount() {
			return 1;
		}

		public boolean hasStableIds() {
			return false;
		}

		public boolean isEmpty() {
			return this.clientList.isEmpty();
		}

		public void registerDataSetObserver(DataSetObserver observer) {
			// TODO Auto-generated method stub

		}

		public void unregisterDataSetObserver(DataSetObserver observer) {
			// TODO Auto-generated method stub

		}

		public boolean areAllItemsEnabled() {
			return true;
		}

		public boolean isEnabled(int position) {
			return true;
		}

	}

}
